package com.test.videoplayer.activity.play;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.dueeeke.videocontroller.StandardVideoController;
import com.dueeeke.videoplayer.ijk.IjkPlayerFactory;
import com.dueeeke.videoplayer.listener.OnVideoViewStateChangeListener;
import com.dueeeke.videoplayer.player.VideoView;
import com.dueeeke.videoplayer.util.L;
import com.test.videoplayer.helper.IntentKeys;
import com.test.videoplayer.R;
import com.test.videoplayer.BaseActivity;
import com.test.videoplayer.helper.NetSpeedTimer;
import com.timmy.tdialog.TDialog;

/**
 * 播放器演示
 * Created by Devlin_n on 2017/4/7.
 */

public class PlayerActivity extends BaseActivity implements Handler.Callback {
    private NetSpeedTimer mNetSpeedTimer;
    private VideoView mVideoView;
    private ImageView mTitleMenu;//菜单
    private TextView tvStreamBps;
    public static TDialog menuTDialog = null;
    private long mSpeedLength;
    private boolean isLive = false;
    private final Handler mHandler = new Handler();
    private final Runnable mTimerRunnable = new Runnable() {
        @SuppressLint("SetTextI18n")
        @Override
        public void run() {
            mSpeedLength = mVideoView.getTcpSpeed();
            L.e("mSpeedLength :" + mSpeedLength);
            if (isLive && mSpeedLength == 0) {
                mVideoView.onError();
            }
            tvStreamBps.setText(mSpeedLength / 1024 + "Kbps");
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("Player");
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        tvStreamBps = findViewById(R.id.tvStreamBps);
        mVideoView = findViewById(R.id.player);
        getNetSpeed(mVideoView);
        mVideoView.setClickable(false);
        Intent intent = getIntent();
        if (intent != null) {
            StandardVideoController controller = new StandardVideoController(this);
            controller.setOnClickListener(v -> {
                Log.d("Tag", "111111111111111");
                //mVideoView.release();
            });
            isLive = intent.getBooleanExtra("isLive", false);
            if (isLive) {
                controller.setLive();
            }
            String title = intent.getStringExtra(IntentKeys.TITLE);
            controller.setTitle(title);
            mVideoView.setVideoController(controller);
            mTitleMenu = controller.findViewById(R.id.iv_titleMenu);
            mTitleMenu.setOnClickListener(v -> {
                showToast();
            });
            mVideoView.setUrl(intent.getStringExtra(IntentKeys.URL));
            //保存播放进度
//            mVideoView.setProgressManager(new ProgressManagerImpl());
            //播放状态监听
            mVideoView.addOnVideoViewStateChangeListener(mOnVideoViewStateChangeListener);

            //使用IjkPlayer解码
            mVideoView.setPlayerFactory(IjkPlayerFactory.create(this));
            //使用ExoPlayer解码
//            mVideoView.setPlayerFactory(ExoMediaPlayerFactory.create(this));
            //使用MediaPlayer解码
//            mVideoView.setPlayerFactory(AndroidMediaPlayerFactory.create(this));

//            mVideoView.setPlayerFactory(new PlayerFactory() {
//                @Override
//                public AbstractPlayer createPlayer() {
//                    return new ExoMediaPlayer(PlayerActivity.this) {
//
//                        @Override
//                        protected LoadControl getLoadControl() {
//                            return super.getLoadControl();
//                        }
//
//                        @Override
//                        public void setOptions() {
//                            super.setOptions();
//                        }
//                    };
//                }
//            });
            //设置播放器一直处于横屏状态
            mVideoView.setAutoRotate(false);
            mVideoView.start();
            mVideoView.setVolume(0f, 0f);
           // mVideoView.setMute(true);
        }
    }

    private void getNetSpeed(VideoView player) {
        Handler handler = new Handler(PlayerActivity.this);
        //创建NetSpeedTimer实例
        mNetSpeedTimer = new NetSpeedTimer(this, 1, player, handler).setDelayTime(1000).setPeriodTime(2000);
        mNetSpeedTimer.startSpeedTimer();
    }

    @Override
    protected VideoView getVideoView() {
        return mVideoView;
    }

    private OnVideoViewStateChangeListener mOnVideoViewStateChangeListener = new OnVideoViewStateChangeListener() {
        @Override
        public void onPlayerStateChanged(int playerState) {
            switch (playerState) {
                case VideoView.PLAYER_NORMAL://小屏
                    break;
                case VideoView.PLAYER_FULL_SCREEN://全屏
                    break;
            }
        }

        @Override
        public void onPlayStateChanged(int playState) {
            //在想要开始执行的地方调用该段代码
            switch (playState) {
                case VideoView.STATE_IDLE:
                    break;
                case VideoView.STATE_PREPARING:
                    mHandler.post(mTimerRunnable);
                    // mHandler.postDelayed(mTimerRunnable);
                    break;
                case VideoView.STATE_PREPARED:
                    //需在此时获取视频宽高
                    int[] videoSize = mVideoView.getVideoSize();
                    L.d("视频宽：" + videoSize[0]);
                    L.d("视频高：" + videoSize[1]);
                    break;
                case VideoView.STATE_PLAYING:
                    break;
                case VideoView.STATE_PAUSED:
                    break;
                case VideoView.STATE_BUFFERING:
                    //mHandler.postDelayed(mTimerRunnable, 6000);
                    break;
                case VideoView.STATE_BUFFERED:
                    break;
                case VideoView.STATE_PLAYBACK_COMPLETED:
                    break;
                case VideoView.STATE_ERROR:
                    break;
            }
        }
    };

    @SuppressLint("SetTextI18n")
    @Override
    public boolean handleMessage(Message msg) {
        // TODO Auto-generated method stub
       /* if (msg.what == NetSpeedTimer.NET_SPEED_TIMER_DEFAULT) {
            int type = msg.arg1;
            Long speed = (Long) msg.obj;
            if (type == 1) {
                tvStreamBps.setText(speed / 3072 + "Kbps");
            }
            //打印你所需要的网速值，单位默认为kb/s
            //tvStreamBps1.setText(speed / 3072 + "Kbps");
            Log.e("Tag", "数据格式类型  = " + type);
            Log.e("Tag", "current net speed  = " + speed + "kb/s");
        }*/
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    protected void onPause() {
        super.onPause();
        mVideoView.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mVideoView.resume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mVideoView.release();
        if (null != mNetSpeedTimer) {
            mNetSpeedTimer.stopSpeedTimer();
        }
    }


    @Override
    public void onBackPressed() {
        L.e("onBackPressed");
        if (!mVideoView.onBackPressed()) {
            super.onBackPressed();
        }
    }

    public void screenScaleDefault(View view) {
        mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_DEFAULT);
    }

    public void screenScale169(View view) {
        mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_16_9);
    }

    public void screenScale43(View view) {
        mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_4_3);
    }

    public void screenScaleOriginal(View view) {
        mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_ORIGINAL);
    }

    public void screenScaleMatch(View view) {
        mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_MATCH_PARENT);
    }

    public void screenScaleCenterCrop(View view) {
        mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_CENTER_CROP);
    }

    int i = 0;

    public void setMirrorRotate(View view) {
        mVideoView.setMirrorRotation(i % 2 == 0);
        i++;
    }

    public void showToast() {
        menuTDialog = new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_video_menu)    //设置弹窗展示的xml布局
                .setScreenHeightAspect(PlayerActivity.this, 1.0f)  //设置弹窗高度(参数aspect为屏幕宽度比例 0 - 1f)
                .setDimAmount(0f)
                .setOnBindViewListener(viewHolder -> {
                    //TextView text = viewHolder.getView(R.id.btnMoRen);
                })
                .setOnDismissListener(dialog -> Toast.makeText(PlayerActivity.this, "cancel", Toast.LENGTH_SHORT).show())
                .addOnClickListener(
                        R.id.btnMoRen,
                        R.id.btnTianZhong,
                        R.id.btnZiShiY,
                        R.id.btnCenterCaiJ,
                        R.id.btnPlay1,
                        R.id.btnPlay2,
                        R.id.btnPlay3,
                        R.id.btnPlay4,
                        R.id.btnPlay5,
                        R.id.btnXuanZ,
                        R.id.btnSetting)
                .setOnViewClickListener((viewHolder, view, tDialog) -> {
                    switch (view.getId()) {
                        case R.id.btnMoRen:
                            mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_DEFAULT);
                            tDialog.dismiss();
                            break;
                        case R.id.btnTianZhong:
                            mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_MATCH_PARENT);
                            tDialog.dismiss();
                            break;
                        case R.id.btnZiShiY:
                            mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_ORIGINAL);
                            tDialog.dismiss();
                            break;
                        case R.id.btnCenterCaiJ:
                            mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_CENTER_CROP);
                            tDialog.dismiss();
                            break;
                        case R.id.btnPlay1:
                            mVideoView.setSpeed(0.5f);
                            tDialog.dismiss();
                            break;
                        case R.id.btnPlay2:
                            mVideoView.setSpeed(0.75f);
                            tDialog.dismiss();
                            break;
                        case R.id.btnPlay3:
                            mVideoView.setSpeed(1.0f);
                            tDialog.dismiss();
                            break;
                        case R.id.btnPlay4:
                            mVideoView.setSpeed(1.5f);
                            tDialog.dismiss();
                            break;
                        case R.id.btnPlay5:
                            mVideoView.setSpeed(2.0f);
                            tDialog.dismiss();
                            break;
                        case R.id.btnXuanZ:
                            setMirrorRotate1();
                            tDialog.dismiss();
                            break;
                        case R.id.btnSetting:
                            setVolume();
                            tDialog.dismiss();
                            break;
                       /* case R.id.tDialogContainer:
                            tDialog.dismiss();
                            break;*/
                    }
                })
                .setCancelableOutside(true)
                .setGravity(Gravity.RIGHT)
                .create()   //创建TDialog
                .show();    //展示
    }

    public void setSpeed0_75(View view) {
        mVideoView.setSpeed(0.75f);
    }

    public void setSpeed0_5(View view) {
        mVideoView.setSpeed(0.5f);
    }

    public void setSpeed1_0(View view) {
        mVideoView.setSpeed(1.0f);
    }

    public void setSpeed1_5(View view) {
        mVideoView.setSpeed(1.5f);
    }

    public void setSpeed2_0(View view) {
        mVideoView.setSpeed(2.0f);
    }

    public void setMirrorRotate1() {
        mVideoView.setMirrorRotation(i % 2 == 0);
        i++;
    }

    boolean isTrue = true;

    public void setVolume() {
        if (isTrue) {
            mVideoView.setVolume(0f, 0f);
            isTrue = false;
        } else {
            mVideoView.setVolume(0f, 50f);
            isTrue = true;
        }
    }
}
